<template>
  <div v-loading="loading">
    <el-table :data="tableData" border highlight-current-row class="weekly-table">
      <el-table-column prop="mealType" label="餐别" width="120" fixed>
        <template #default="scope">
          <span>{{ getMealTypeName(scope.row.mealType) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(day, index) in weekDays"
        :key="index"
        :prop="'day' + (index + 1)"
        :label="day.date ? `${day.label}(${day.date})` : day.label"
        min-width="180"
      >
        <template #default="scope">
          <div
            class="recipe-cell cursor-pointer hover:bg-gray-100 p-4px rounded h-full"
            @click="editRecipe(scope.row[`day${index + 1}`], scope.row.mealType, index + 1)"
          >
            <div
              v-if="
                scope.row[`day${index + 1}`] &&
                scope.row[`day${index + 1}`].recipeList &&
                scope.row[`day${index + 1}`].recipeList.length > 0
              "
            >
              <div
                v-for="(recipe, rIndex) in scope.row[`day${index + 1}`].recipeList"
                :key="rIndex"
                class="recipe-item mb-2px"
              >
                <div class="flex justify-between items-center">
                  <span class="recipe-name text-14px">{{ recipe.recipeName }}</span>
                  <span class="food-usage text-12px text-gray-500">{{ recipe.totalUsages }}克</span>
                </div>
              </div>
            </div>
            <div
              v-else
              class="empty-cell text-gray-400 text-center h-full w-full flex items-center justify-center"
            >
              点击添加
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 菜谱编辑弹窗 -->
  <RecipeMenusForm ref="recipeMenusFormRef" @save="handleSaveRecipeMenus" />
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { RecipeMenusDailyApi } from '@/api/school/recipe/menusDaily'
import RecipeMenusForm from '../RecipeMenusForm.vue'

// 定义组件属性
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  currentWeeklyMenu: {
    type: Object,
    default: () => ({})
  }
})

// 定义事件
const emit = defineEmits(['update:loading'])

const message = useMessage()

// 周食谱数据
const weeklyRecipes = ref<any[]>([])

// 餐别选项
const mealTypes = getStrDictOptions(DICT_TYPE.SCHOOL_MEAL_TYPE)

// 星期选项
const weekDays = computed(() => {
  const days = [
    { label: '周一', value: 1 },
    { label: '周二', value: 2 },
    { label: '周三', value: 3 },
    { label: '周四', value: 4 },
    { label: '周五', value: 5 },
    { label: '周六', value: 6 },
    { label: '周日', value: 7 }
  ]

  // 创建一个映射，将weekDay值映射到日期
  const dateMap: Record<string, string> = {}

  // 从weeklyRecipes中获取日期信息
  if (weeklyRecipes.value && weeklyRecipes.value.length > 0) {
    weeklyRecipes.value.forEach((item: any) => {
      if (item.weekDay && item.menuDate) {
        dateMap[item.weekDay] = formatDate(new Date(item.menuDate), 'MM.DD')
      }
    })
  }

  // 如果weeklyRecipes中没有足够的数据，从currentWeeklyMenu中计算日期
  if (
    props.currentWeeklyMenu &&
    props.currentWeeklyMenu.weekYear &&
    props.currentWeeklyMenu.weekNumber
  ) {
    // 计算这一周的每一天日期
    const startDate = getWeekStartDate(
      props.currentWeeklyMenu.weekYear,
      props.currentWeeklyMenu.weekNumber
    )

    days.forEach((day) => {
      // 如果dateMap中还没有这个日期，则计算并添加
      if (!dateMap[day.value]) {
        const currentDate = new Date(startDate)
        currentDate.setDate(startDate.getDate() + day.value - 1) // 周一为第一天
        dateMap[day.value] = formatDate(currentDate, 'MM.DD')
      }
    })
  }

  // 将日期信息添加到days数组中
  return days.map((day) => ({
    ...day,
    date: dateMap[day.value] || '' // 如果仍然没有日期，则显示空字符串
  }))
})

// 根据年份和周数获取周开始日期
const getWeekStartDate = (year: number, week: number) => {
  // 使用一个更准确的计算方法
  // 创建该年的第一天
  const januaryFirst = new Date(year, 0, 1)

  // 获取该年第一周的周四（用于确定第一周）
  const firstThursday = new Date(januaryFirst)
  firstThursday.setDate(januaryFirst.getDate() + ((11 - januaryFirst.getDay()) % 7))

  // 获取第一周的周一
  const firstMonday = new Date(firstThursday)
  firstMonday.setDate(firstThursday.getDate() - 3)

  // 计算目标周的周一日期
  const targetMonday = new Date(firstMonday)
  targetMonday.setDate(firstMonday.getDate() + (week - 1) * 7)

  return targetMonday
}

// 表格数据
const tableData = computed(() => {
  // 按餐别分组数据
  const groupedData: any[] = []

  mealTypes.forEach((meal) => {
    const mealData: any = {
      mealType: meal.value
    }

    // 为每一天初始化数据
    weekDays.value.forEach((day, index) => {
      // 为未安排的单元格提供基础数据结构
      mealData[`day${index + 1}`] = {
        mealType: meal.value,
        weekDay: (index + 1).toString(),
        recipeList: [], // 每个单元格都有独立的数组引用
        menuDate: getDateForWeekDay(index + 1) // 获取对应星期的时间戳
      }
    })

    // 填充实际数据
    weeklyRecipes.value.forEach((item: any) => {
      const dayIndex = parseInt(item.weekDay)
      if (item.mealList) {
        item.mealList.forEach((mealItem: any) => {
          if (mealItem.mealType === meal.value) {
            // 保存整个mealItem对象，包含recipeList和menuDate
            mealData[`day${dayIndex}`] = {
              ...mealItem,
              menuDate: item.menuDate // menuDate 已经是时间戳，直接使用
            }
          }
        })
      }
    })

    groupedData.push(mealData)
  })

  return groupedData
})

// 获取指定星期几的日期时间戳
const getDateForWeekDay = (weekDay: number) => {
  // 从weekDays中查找对应星期几的日期
  const dayInfo = weekDays.value.find((day) => day.value === weekDay)
  if (dayInfo && dayInfo.date) {
    // 从currentWeeklyMenu获取年份信息
    const year = props.currentWeeklyMenu?.weekYear || new Date().getFullYear()
    // 将 MM.DD 格式的日期转换为完整日期
    const [month, day] = dayInfo.date.split('.')
    const dateStr = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
    const date = new Date(dateStr)
    // 确保时间戳准确（设置为当天的开始时间）
    date.setHours(0, 0, 0, 0)
    return date.getTime() // 返回时间戳
  }
  return null
}

// 获取餐别名称
const getMealTypeName = (mealType: string) => {
  const meal = mealTypes.find((item) => item.value === mealType)
  return meal ? meal.label : mealType
}

// 保存当前编辑的位置信息
const currentEditInfo = ref<{
  mealType: string
  dayIndex: number
} | null>(null)

// 菜谱编辑弹窗引用
const recipeMenusFormRef = ref()

// 编辑菜谱
const editRecipe = (mealItem: any, mealType: string, weekDay: number) => {
  // 保存当前编辑的位置信息
  currentEditInfo.value = {
    mealType: mealType,
    dayIndex: weekDay
  }

  // 处理未安排的单元格，确保有正确的数据结构
  const actualMealItem = mealItem || {
    mealType: mealType,
    weekDay: weekDay.toString(),
    recipeList: [],
    menuDate: getDateForWeekDay(weekDay)
  }

  const data = {
    menuId: props.currentWeeklyMenu.menuId,
    mealType: mealType,
    weekDay: weekDay.toString(),
    menuDate: actualMealItem.menuDate,
    recipeList: actualMealItem.recipeList,
    totalUsages: actualMealItem.totalUsages
  }

  recipeMenusFormRef.value.open(data)
}

// 保存菜谱后的回调
const handleSaveRecipeMenus = async (result?: any) => {
  // 重新加载当前周食谱详情
  await loadWeeklyMenuDetail(props.currentWeeklyMenu.menuId)

  // 保存当前编辑的位置信息
  const editInfo = currentEditInfo.value

  // 如果有编辑位置信息，重新打开编辑弹窗
  if (editInfo) {
    // 根据保存的位置信息找到对应的数据
    let targetCell: any = null

    for (const mealData of tableData.value) {
      if (mealData.mealType === editInfo.mealType && mealData[`day${editInfo.dayIndex}`]) {
        targetCell = mealData[`day${editInfo.dayIndex}`]
        break
      }
    }

    // 如果找到了对应的数据，重新打开编辑弹窗
    if (targetCell) {
      editRecipe(targetCell, editInfo.mealType, editInfo.dayIndex)
    }
  }
}

// 加载周食谱详情
const loadWeeklyMenuDetail = async (menuId: number) => {
  emit('update:loading', true)
  try {
    // 获取食材用量详情
    weeklyRecipes.value = await RecipeMenusDailyApi.getRecipeMenusDailyUsage(menuId)
  } catch (err) {
    message.error('加载周食谱详情失败')
  } finally {
    emit('update:loading', false)
  }
}

// 监听currentWeeklyMenu变化，当menuId改变时重新加载数据
watch(
  () => props.currentWeeklyMenu?.menuId,
  async (newMenuId, oldMenuId) => {
    if (newMenuId && newMenuId !== oldMenuId) {
      await loadWeeklyMenuDetail(newMenuId)
    }
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  recipeMenusFormRef,
  loadWeeklyMenuDetail
})
</script>

<style lang="scss" scoped>
.weekly-table {
  :deep(.el-table__cell) {
    padding: 8px 0;
  }

  .recipe-cell {
    height: 100%;
    min-height: 60px;
  }
}
</style>
